'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url agent/callback/pub/send_test 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let nows = new Date().getTime()

		const crypto = require('crypto');
		const sha1 = crypto.createHash('sha1');

		let times = vk.pubfn.toDecimal(new Date() / 1000, 0);
		// let times = 1677108304;
		console.log("times=", times);
		let beforesha1 = "54d08a85eafc4bb98bebad5b266636e5" + "fc1c8cc3b64b4253b1dbcf5cfac2540e" + times;
		let sign = sha1.update(beforesha1).digest('hex');

		console.log("sign=", sign);


		//1.加密 
		let input = "1000218511,54d08a85eafc4bb98bebad5b266636e5," + times + "," + sign;
		console.log("input=", input);
		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		// input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		console.log("output=", output);



		// 回传支付事件给百度
		let baiduurl = "https://sapi.ads.oppomobile.com/v1/clue/sendData"
		let baiduhuichuan_result = await uniCloud.httpclient.request(baiduurl, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				Authorization: "Bearer " + output
			},
			data: {
				"ip": "117.154.53.120",
				"transformType": 101,
				"ownerId": "1000218511",
				"pageId": "1200032371",
				"tid": "1-HiNCYSL9RtvV5etEswZ6uemL4OKEaxS3NTLLzsIvsWxmgvu4Ey6JL%2BvE%2F4gE%2BKDF1677110117ApiTestTidProfix",
				"items": [{
						"column": "姓名",
						"desc": "姓名输入框",
						"ifNeed": true,
						"type": "1",
						"value": "小红"
					},
					{
						"column": "电话",
						"desc": "电话",
						"ifNeed": true,
						"type": "3",
						"value": "18783687596"
					}
				],
				"lbid": "1_0_0"
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' // 指定返回值为json格式，自动进行parse
		})

		// 回传记录入库
		let addhc1 = await db.collection('jl_huichuanjilu').add({
			type: "active_pay",
			platform: "OPPO",
			result: baiduhuichuan_result.data,
			time: nows,
			time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
		})



		// 业务逻辑结束-----------------------------------------------------------
		return addhc1;

	}
}
